<?php
class ImageGallery
{
	private $allowedExtensions = array("jpg","jpeg","gif","png");
	
	//FileUpload object
	private $fileUpload;
	
	public function __construct()
	{
		$this->fileUpload = new FileUpload('imageGallery');
		$this->fileUpload->setAllowedExtensions($this->allowedExtensions);
	}
	
	public function main($msg = '')
	{
		$html = $msg ? '<h2>'.$msg.'</h2>': '';
		$html .= $this->fileUpload->getFormHtml();
		$html .= $this->getGalleryHtml();
		return $html;
	}
	
	public function getGalleryHtml()
	{
		ob_start();
		$html = ob_get_contents();
		ob_get_clean();
		return $html;
	}
	
	private function encode($data)
	{
		$data = base64_encode($data);
		//$data = gzcompress($data);
		return $data;
	}
	
	private function decode($data)
	{
		//$data = gzuncompress($data);
		$data = base64_decode($data);
		return $data;
	}
	
	public function save()
	{
		require_once 'Classes/DbConn.php';
		$db = DbConn::getInstance()->getConn();
		$imageData = $this->fileUpload->getFileData();
		$data = $this->encode($imageData['data']);
		$type = $imageData['type'];
		$name = $imageData['name'];
		$sql = 'INSERT INTO images(name, type, data) VALUES ("'.$name.'", "'.$type.'", "'.$data.'")';
		return $db->query($sql);
	}
	
	public function display($imageId)
	{
		$imageId = (int)$imageId;
		require_once 'Classes/DbConn.php';
		$db = DbConn::getInstance()->getConn();
		$sql = "SELECT * FROM images WHERE id = $imageId";
		$result = $db->query($sql);
		$rows = array();
		if($result){
			while ($row = $result->fetch_object()) {
				$rows[] = $row;
			}
			$result->close();
		}
		if($rows){
			header("Content-Type: ".$rows[0]->type);
			echo $this->decode($rows[0]->data);
		}
	}
	
	public function upload()
	{
		if($this->fileUpload->isUploadedFile()){
			$this->save();
			$message = 'file was uploaded';
		}else{
			$message = $this->fileUpload->getErrorMessage();
		}
		return $this->main($message);
	}
}